import { useCallback, useState } from 'react';
export const useAsync = () => {
  const [data, setData] = useState<any>(null);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState(false);
  const run = useCallback((promise: Promise<any>) => {
    setLoading(true);
    promise
      .then(data => {
        setData(data);
        setTimeout(() => setLoading(false), 2000);
      })
      .catch(e => {
        setError(e);
        setTimeout(() => setLoading(false), 2000);
      });
  }, []);
  return {
    run,
    data,
    error,
    loading,
  };
};

/* export const useHttp = () => {
  const { user } = useAuth();
  // utility type 的用法：用泛型给它传入一个其他类型，然后utility type对这个类型进行某种操作
  return useCallback(
    (...[endpoint, config]: Parameters<typeof http>) =>
      http(endpoint, { ...config, token: user?.token }),
    [user?.token]
  );
}; */
